#!/bin/bash

#####################################################################
# 腾讯云服务器环境配置脚本
# 功能：自动安装JDK 21、MySQL，并配置基础环境
#####################################################################

set -e  # 遇到错误立即退出

# 颜色定义
RED='\033[0;31m'
GREEN='\033[0;32m'
YELLOW='\033[1;33m'
BLUE='\033[0;34m'
NC='\033[0m'

# 打印函数
print_info() {
    echo -e "${BLUE}[INFO]${NC} $1"
}

print_success() {
    echo -e "${GREEN}[SUCCESS]${NC} $1"
}

print_warning() {
    echo -e "${YELLOW}[WARNING]${NC} $1"
}

print_error() {
    echo -e "${RED}[ERROR]${NC} $1"
}

# 检测操作系统
detect_os() {
    if [ -f /etc/os-release ]; then
        . /etc/os-release
        OS=$ID
        VER=$VERSION_ID
    else
        print_error "无法检测操作系统版本"
        exit 1
    fi
    
    print_info "检测到操作系统: $OS $VER"
}

# 更新系统
update_system() {
    print_info "更新系统包..."
    
    if [ "$OS" = "centos" ] || [ "$OS" = "rhel" ]; then
        sudo yum update -y
    elif [ "$OS" = "ubuntu" ] || [ "$OS" = "debian" ]; then
        sudo apt update && sudo apt upgrade -y
    fi
    
    print_success "系统更新完成"
}

# 安装JDK 21
install_jdk21() {
    print_info "开始安装JDK 21..."
    
    # 检查是否已安装
    if [ -d "/usr/local/java/jdk-21" ]; then
        print_warning "JDK 21 已安装，跳过"
        return 0
    fi
    
    # 创建目录
    sudo mkdir -p /usr/local/java
    cd /tmp
    
    # 下载JDK 21
    print_info "正在下载JDK 21..."
    wget -q --show-progress https://builds.openlogic.com/downloadJDK/openlogic-openjdk/21.0.1+12/openlogic-openjdk-21.0.1+12-linux-x64.tar.gz
    
    if [ $? -ne 0 ]; then
        print_error "JDK下载失败，请检查网络连接"
        exit 1
    fi
    
    # 解压
    print_info "正在解压JDK..."
    sudo tar -zxf openlogic-openjdk-21.0.1+12-linux-x64.tar.gz -C /usr/local/java/
    sudo mv /usr/local/java/openlogic-openjdk-21.0.1+12-linux-x64 /usr/local/java/jdk-21
    
    # 配置环境变量
    print_info "配置环境变量..."
    if ! grep -q "JAVA_HOME=/usr/local/java/jdk-21" /etc/profile; then
        sudo tee -a /etc/profile > /dev/null <<EOF

# Java Environment
export JAVA_HOME=/usr/local/java/jdk-21
export PATH=\$JAVA_HOME/bin:\$PATH
export CLASSPATH=.:\$JAVA_HOME/lib
EOF
    fi
    
    # 使环境变量生效
    source /etc/profile
    
    # 验证安装
    JAVA_VER=$(/usr/local/java/jdk-21/bin/java -version 2>&1 | head -n 1)
    print_success "JDK 21 安装成功: $JAVA_VER"
    
    # 清理
    rm -f /tmp/openlogic-openjdk-21.0.1+12-linux-x64.tar.gz
}

# 安装MySQL
install_mysql() {
    print_info "开始安装MySQL..."
    
    if [ "$OS" = "centos" ] || [ "$OS" = "rhel" ]; then
        # CentOS/RHEL
        if systemctl is-active --quiet mysqld; then
            print_warning "MySQL 已安装并运行，跳过"
            return 0
        fi
        
        print_info "下载MySQL仓库..."
        cd /tmp
        wget -q https://dev.mysql.com/get/mysql80-community-release-el8-1.noarch.rpm
        sudo rpm -ivh mysql80-community-release-el8-1.noarch.rpm
        
        print_info "安装MySQL服务器..."
        sudo yum install mysql-server -y
        
        print_info "启动MySQL..."
        sudo systemctl start mysqld
        sudo systemctl enable mysqld
        
        # 获取临时密码
        TEMP_PASS=$(sudo grep 'temporary password' /var/log/mysqld.log | awk '{print $NF}')
        print_success "MySQL安装完成"
        print_warning "MySQL临时root密码: $TEMP_PASS"
        print_warning "请运行 'sudo mysql_secure_installation' 进行安全配置"
        
    elif [ "$OS" = "ubuntu" ] || [ "$OS" = "debian" ]; then
        # Ubuntu/Debian
        if systemctl is-active --quiet mysql; then
            print_warning "MySQL 已安装并运行，跳过"
            return 0
        fi
        
        print_info "安装MySQL服务器..."
        sudo apt install mysql-server -y
        
        print_info "启动MySQL..."
        sudo systemctl start mysql
        sudo systemctl enable mysql
        
        print_success "MySQL安装完成"
        print_warning "请运行 'sudo mysql_secure_installation' 进行安全配置"
    fi
}

# 配置防火墙
configure_firewall() {
    print_info "配置防火墙..."
    
    if [ "$OS" = "centos" ] || [ "$OS" = "rhel" ]; then
        if command -v firewall-cmd &> /dev/null; then
            sudo firewall-cmd --permanent --add-port=8086/tcp
            sudo firewall-cmd --reload
            print_success "防火墙已开放8086端口"
        fi
    elif [ "$OS" = "ubuntu" ] || [ "$OS" = "debian" ]; then
        if command -v ufw &> /dev/null; then
            sudo ufw allow 22/tcp  # SSH
            sudo ufw allow 8086/tcp
            print_success "防火墙已开放8086端口"
            print_warning "请手动启用UFW: sudo ufw enable"
        fi
    fi
}

# 创建应用目录
create_app_directory() {
    print_info "创建应用目录..."
    
    sudo mkdir -p /opt/kaizeli
    sudo mkdir -p /opt/kaizeli/logs
    sudo mkdir -p /opt/backups
    
    print_success "应用目录已创建: /opt/kaizeli"
}

# 显示MySQL配置提示
show_mysql_config_tips() {
    cat <<EOF

${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}
${GREEN}  MySQL配置提示${NC}
${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}

${YELLOW}1. 运行安全配置${NC}
   sudo mysql_secure_installation

${YELLOW}2. 登录MySQL${NC}
   sudo mysql -u root -p

${YELLOW}3. 创建数据库和用户（在MySQL命令行中执行）${NC}
   ${BLUE}CREATE DATABASE kaizeli DEFAULT CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
   CREATE USER 'kaizeli_user'@'localhost' IDENTIFIED BY 'your_password_here';
   GRANT ALL PRIVILEGES ON kaizeli.* TO 'kaizeli_user'@'localhost';
   FLUSH PRIVILEGES;
   EXIT;${NC}

${YELLOW}4. 导入数据库SQL文件（如果有）${NC}
   mysql -u kaizeli_user -p kaizeli < /path/to/database.sql

EOF
}

# 显示完成信息
show_completion_message() {
    cat <<EOF

${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}
${GREEN}  🎉 服务器环境配置完成！${NC}
${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}

${BLUE}✅ 已完成：${NC}
   - 系统更新
   - JDK 21 安装
   - MySQL 安装
   - 防火墙配置
   - 应用目录创建

${BLUE}📝 下一步操作：${NC}
   1. 配置MySQL数据库（见上方提示）
   2. 上传JAR包到服务器
   3. 创建应用配置文件
   4. 部署并启动应用

${BLUE}🔍 验证命令：${NC}
   - Java版本: ${YELLOW}java -version${NC}
   - MySQL状态: ${YELLOW}sudo systemctl status mysqld${NC} (CentOS)
                ${YELLOW}sudo systemctl status mysql${NC} (Ubuntu)
   - 防火墙: ${YELLOW}sudo firewall-cmd --list-ports${NC} (CentOS)
            ${YELLOW}sudo ufw status${NC} (Ubuntu)

${BLUE}📖 详细部署指南：${NC}
   查看 腾讯云部署指南.md

${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}

EOF
}

# 主函数
main() {
    clear
    
    cat <<EOF
${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}
${GREEN}  腾讯云服务器环境自动配置脚本${NC}
${GREEN}  Kaizeli项目管理系统${NC}
${GREEN}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━${NC}

EOF
    
    # 检查是否为root
    if [ "$EUID" -ne 0 ] && ! sudo -n true 2>/dev/null; then
        print_error "请使用root用户或具有sudo权限的用户运行此脚本"
        exit 1
    fi
    
    detect_os
    echo ""
    
    update_system
    echo ""
    
    install_jdk21
    echo ""
    
    install_mysql
    echo ""
    
    configure_firewall
    echo ""
    
    create_app_directory
    echo ""
    
    show_mysql_config_tips
    show_completion_message
}

# 运行主函数
main

